/*
 广告账号列表页
 */
define([
    '../../common/service',
    '../../../app/framework/bean/connectionobjects',
    '../../../app/framework/bean/entrustaccounts',
    '../../../app/framework/bean/menu',
    '../../../app/framework/bean/organization',
    '../../../app/framework/bean/user',
    '../../../app/framework/bean/version'
], function(
    http,
    connectionobjectsModel,
    entrustaccountsModel,
    menuModel,
    organizationModel,
    userModel,
    versionModel
) {
    $.fn.select2.amd.require(['select2/selection/search'], function(Search) {
        var oldRemoveChoice = Search.prototype.searchRemoveChoice;
        Search.prototype.searchRemoveChoice = function() {
            oldRemoveChoice.apply(this, arguments);
            this.$search.val('');
        };
    });

    var Widget = function() {}
    Widget.prototype = $.extend(Widget.prototype, {
        init: function() {
            var _this = this;
            //列表管理
            $('table[list-manager="entrustAccountList"]').listManager('init', {
                setTopVal:227//调整吸顶的高度,需要减去这个高度
                ,scrollDOM:$('.fmp-article'),//监听滚动条
                isRealTime: true,
                supportAjaxPage: true,
                supportConfig:false,
                pageCallback: function(query) {
                    $.extend(_this._query, query);
                    _this.entrustAccountList();
                }
            }, function(query) {
                _this._query = query;
                _this.bindBusinessTabsEvent();
                //_this.bindSyncEvent();            //绑定同步事件
                _this.businessManagers();
                _this.bindAddEvent(); //绑定BM增加账号事件
                //_this.bindUnbindEvent();      //绑定解绑功能  bug：需要在列表刷出來才能绑定
                _this.cacheKey =$('table[list-manager="entrustAccountList"]').listManager('getListManager').cacheKey;
            });

        },
        bindAddEvent: function() {
                var _this = this,
                    addArea = $('.add-area'),
                    addAction = addArea.find('.add-action'),
                    getData = addArea.find('.get-data');
                addAction.unbind('clcik');
                addAction.click(function() {
                    _this.reset();
                    getData.show();
                });
                getData.unbind('click');
                getData.click(function() {
                    _this.businessManagers();
                });
                $('#sync-history-action').click(function(event) {
                    var loadingArea = $('#con-area');
                    Kit.loading.show(loadingArea);
                    http.do('/entrustaccounts/accountOperateHistoryList', { param: '' }, 'GET').then(function(res) {
                        var data = res.data;
                        var tpl = _.template($('#t-history').text())(data);
                        $('#dialog-history').find(".modal-body").html(tpl);
                        $('#dialog-history').modal('show');
                        Kit.loading.hide(loadingArea);
                    }, function(msg, data, type, errorCode) {
                        Kit.loading.hide(loadingArea);
                        Kit.alert2(I18N.getText('account', 'getListFail'));
                    });
                });

                //绑定同步按钮
                $('#sync-confirm-action').click(function(event) {
                    var loadingArea = $('#con-area');
                    Kit.loading.show(loadingArea);
                    _this.reset();
                    http.do('/entrustaccounts/changeAccountList', { param: '' }, 'POST').then(function(res) {
                        var data = res.data;
                        if (res.flag == 'success') {
                            if (data.recycleAccounts.length == 0 && data.appendAccounts.length == 0 && data.changeAccounts.length == 0) {
                                Kit.alert_info(I18N.getText('account', 'noUpdate'));
                                Kit.loading.hide(loadingArea);
                                return;
                            }
                            var tpl = _.template($('#t-sync-confirm').text())(data);
                            $('#dialog-sync-confirm').find(".modal-body").html(tpl);
                            $('#dialog-sync-confirm').modal('show');
                            $('#dialog-sync-confirm').find('.synaccountBtn').off('click');
                            $('#dialog-sync-confirm').find('.synaccountBtn').on('click', synFun);
                            $('#CheckAll').click(function() {
                                $('input[name="checkbox-inline"]').prop("checked", this.checked);
                            });
                            $("input[name='checkbox-inline']").click(function() {
                                var $subs = $("input[name='checkbox-inline']");
                                $("#CheckAll").prop("checked", $subs.length == $subs.filter(":checked").length ? true : false);
                            });
                        } else {
                            Kit.alert2(res.msg || I18N.getText('account', 'getDataFail'))
                        }
                        Kit.loading.hide(loadingArea);
                    }, function() {
                        Kit.loading.hide(loadingArea);
                        Kit.alert2(I18N.getText('account', 'optFail'));
                    }, function() {
                        console.log('over.__defineGetter__.................');
                    });
                });

                function synFun() {
                    var loadingArea = $('#con-area');
                    var newAddIds = [];
                    var updateAddIds = [];
                    var arrChk = $("input[name='checkbox-inline']:checked");
                    //var arrChk=$(".accounts-list:checked");
                    $(arrChk).each(function() {
                        if (this.value != 'on') {
                            newAddIds.push(this.value);
                        }
                    });
                    var arrUpdate = $("input[type='hidden']");
                    $(arrUpdate).each(function() {
                        updateAddIds.push(this.value);
                    })

                    if (newAddIds.length == 0 && updateAddIds.length == 0) {
                        return;
                    }
                    Kit.loading.show(loadingArea);
                    http.do('/entrustaccounts/syncEntrustAccount', {
                        param: JSON.stringify({
                            newAddIds: newAddIds,
                            updateAddIds: updateAddIds
                        })
                    }, 'POST').then(function(res) {
                        Kit.alert_success(I18N.getText('account', 'synSucceedFlush'));
                        _this._query.cPage = 1;
                        _this.businessManagers();
                        Kit.loading.hide(loadingArea);
                    }, function(msg, data, type, errorCode) {
                        Kit.loading.hide(loadingArea);
                        Kit.alert2(I18N.getText('account', 'getDataFail'));
                    });
                }
            }
            /*
             @获取企业及用户信息
             */
        ,businessManagers: function() {
                var _this = this;
                var loadingArea = $(_this.dom);
                var accountArea = $('#bm-account'),
                    businessesArea = $('#bm-businesses'),
                    _tmpHtml = '';
                //Kit.loading.show(loadingArea);
                http.do('/entrustaccounts/businessManagers', { param: '' }, 'POST').then(function(res) {
                    var data = res.data;
                    if (res.flag == "fail") {
                        Kit.loading.hide(loadingArea);
                        //没有bm帐号也没有广告帐号,返回添加帐号的链接
                        var addArea = $('.add-area'),
                            conArea = $('#con-area'),
                            addAction = addArea.find('.add-action');
                        if (res.errorCode == 60101 || res.errorCode == 60024) {
                            conArea.hide();
                            addArea.show();
                            addAction.attr('href', data.addAccountLink);
                            addAction.testRemind(I18N.getText('account', 'addAccount'));
                        } else {
                            Kit.alert2(I18N.getText('account', 'getDataFail'));
                        }
                    } else {
                        //设置bm账号显示
                        $('#con-area').show();
                        if(data.fbUser){
                            var businessManager = data.fbUser;
                            accountArea.html(((typeof(businessManager.name) === "undefined") ? '' : businessManager.name) + ' / ' + ((typeof(businessManager.email) === "undefined") ? '' : businessManager.email));
                        }

                        //配置企业信息
                        var tempArr = [];
                        if(data.businessmanagers){
                            $.each(data.businessmanagers, function(i, e) {
                                _tmpHtml = e.fbBusinessesId + "$#" +  e.name;
                                tempArr.push(_tmpHtml);
                            });
                        }
                        _this._initTabs(tempArr);
                        //businessesArea.eq(0).trigger('TAB_CHANGE');
                        Kit.loading.hide(loadingArea);
                    }
                }, function(msg, data, type, errorCode) {
                    Kit.alert2(I18N.getText('account', 'getDataFail'))
                });
            }
        ,_initTabs:function(tempArr){
            var _this = this;
            var idArr = [],nameArr = [];
            $(tempArr).each(function(i){
                idArr.push(tempArr[i].split("$#")[0]);
                nameArr.push(tempArr[i].split("$#")[1]);
            });
            $("div.ndp-tab-wrapper[name=plain-tab]").empty().tabs({
                list:nameArr
            }).on("TAB_CHANGE",function(e){//点击其中的一个tab发生事件
                _this._query.businessId = idArr[e.originalEvent.data.index];
                _this.entrustAccountList();
            });//设置选中的tab 索引，默认0
            _this._query.businessId = idArr[0];
            _this.entrustAccountList();
        }
        /*
         @绑定公司选项卡事件
         */
        ,bindBusinessTabsEvent: function() {
            var _this = this;
            var businessesArea = $('#bm-businesses');
            businessesArea.off('click', 'li[businesses-id]');
            businessesArea.on('click', 'li[businesses-id]', function() {
                _this._query.businessId = this.getAttribute('businesses-id');
                console.log(_this._query.businessId)
                $('li[businesses-id]', businessesArea).removeClass('active');
                $(this).addClass('active');
                _this.entrustAccountList();
            });
        }
        /*
         @获取广告账号列表数据
         */
        ,entrustAccountList: function() {
                var _this = this;
                var loadingArea = $('#grid').parents('div').eq(0);
                Kit.loading.show(loadingArea);
                http.do('/entrustaccounts/entrustAccountList', { param: JSON.stringify(_this._query) }, 'POST').then(function(res) {
                    //_this.api.API('entrustaccounts', 'entrustAccountList', _this._query).load({
                    //    success: function(msg,data){
                    var data = res.data;
                    //操作DOM节点更换数据
                    var _table = $('table[list-manager="entrustAccountList"]'),
                        _tbody = $('#grid', _table),
                        tmpHtml = '',
                        _list = data.EntrustAccounts;
                    if (!_list || _list.length == 0) {
                        _tbody.html(tmpHtml);
                        _table.listManager('resetPageData', data.paginator);
                        Kit.loading.hide(loadingArea);
                        return;
                    }
                    for (var i = 0; i < _list.length; i++) {
                        tmpHtml += '<tr>' + '<td class="text-center">' + ((data.paginator.cPage - 1) * data.paginator.pSize + i + 1) + '</td>' + '<td title="' + (_list[i].name == '' ? _list[i].fbAccountId : _list[i].name) + '">' + (_list[i].name == '' ? _list[i].fbAccountId : _list[i].name) + '</td>' + '<td title="' + (_list[i].fbAccountId || '') + '">' + (_list[i].fbAccountId || '') + '</td>' + '<td title="' + (_list[i].role || '') + '">' + (_list[i].role || '') + '</td>' + '<td title="' + ((_list[i].balance / 100).toFixed(2)) + '">' + ((_list[i].balance / 100).toFixed(2)) + '</td>' + '<td title="' + (_this.getAccountStatus(_list[i].accountStatus)) + '">' + (_this.getAccountStatus(_list[i].accountStatus)) + '</td>' + '<td title="' + (_list[i].timezone || '') + '">' + (_list[i].timezone || '') + '</td>' + '<td>' + '<span class="cancelBindBtn" title="' + I18N.getText('account', 'cancelbind') + '"  fb-account-id="' + (_list[i].fbAccountId || '') + '">' + '<i class="fa fa-unlink icon-btn"></i></span>' + '</tr>';
                    }
                    _tbody.html(tmpHtml);
                    _table.listManager([{ 'resetTd': false, 'resetPageData': data.paginator }]);
                    _this.bindUnbindEvent();
                    Kit.loading.hide(loadingArea);
                }, function(msg, data, type, errorCode) {
                    Kit.loading.hide(loadingArea);
                    Kit.alert2(msg || I18N.getText('account', 'getDataFail'));
                });
            }
            /*
             @绑定 - 解除绑定事件
             */
            ,
        bindUnbindEvent: function() {
                var _this = this;
                var unbindDialog = $('#dialog-unbind-confirm');
                $('.cancelBindBtn').off('click');
                $('.cancelBindBtn').on('click', function() {
                    var _cancelBindBtn = $(this);
                    unbindDialog.find(".modal-body").html(I18N.getText('account', 'unbindConfirm'));
                    unbindDialog.modal('show');
                    unbindDialog.find('.synaccountBtn').off('click');
                    unbindDialog.find('.synaccountBtn').on('click', function() {
                        var accountId = _cancelBindBtn.attr('fb-account-id');
                        var businessId = _this._query.businessId;
                        unBindAccountApi(accountId, businessId);
                    });
                });

                function unBindAccountApi(accountId, businessId) {
                    var loadingArea = $('#grid').parents('div').eq(0);
                    var par = {
                        entrustAccountId: accountId,
                        fbBussinessId: businessId
                    };
                    Kit.loading.show(loadingArea);
                    http.do('/entrustaccounts/unBindEntrustAccount', { param: JSON.stringify(par) }, 'POST').then(function(res) {
                        //_this.api.API('entrustaccounts', 'unBindEntrustAccount',par).load({
                        //    success: function(msg,data){
                        Kit.alert_success(I18N.getText('account', 'unbindSucceed'));
                        _this._query.cPage = 1;
                        _this.entrustAccountList();
                        Kit.loading.hide(loadingArea);
                    }, function(msg) {
                        Kit.loading.hide(loadingArea);
                        Kit.alert2(msg);
                    });
                }
            }
            /*
             @绑定同步事件
             */
            ,
        bindSyncEvent: function() {
                var _this = this;

                $('body').off('click', '#sync-action');
                $('body').on('click', '#sync-action', function() {
                    //sync.dialog('open');
                    $('#account-dialog').modal('show');
                    $('#account-dialog').find('.synaccountBtn').off('click');
                    $('#account-dialog').find('.synaccountBtn').on('click', syncApi);
                });

                function syncApi() {
                    var loadingArea = $('#grid').parents('div').eq(0);
                    Kit.loading.show(loadingArea);
                    http.do('/entrustaccounts/syncEntrustAccount', { param: '' }, 'POST').then(function(res) {
                        Kit.alert_success(msg || I18N.getText('account', 'getSynSucceed'));
                        _this._query.cPage = 1;
                        _this.businessManagers();
                        Kit.loading.hide(loadingArea);
                    }, function(msg) {
                        Kit.loading.hide(loadingArea);
                        Kit.alert2(msg || I18N.getText('account', 'getSynFail'));
                    });
                }
            }
            /*
             @通过参数获取对应的状态显示文字
             $status:状态值
             */
            ,
        getAccountStatus: function(status) {
            var statusText = '';
            switch (status) {
                case 1:
                    statusText = 'Active';
                    break;
                case 2:
                    statusText = 'Disabled';
                    break;
                case 3:
                    statusText = 'Unsettled';
                    break;
                case 7:
                    statusText = 'Pending Review';
                    break;
                case 9:
                    statusText = 'In Grace Period';
                    break;
                case 100:
                    statusText = 'pending closure';
                    break;
                case 101:
                    statusText = 'temporarily unavailable';
                    break;
                default:
                    statusText = '';
            }
            return statusText;

        },
        /**
         * 清空一些本地缓存
         *
         * @method     reset
         */
        reset: function() {
            localStorage.removeItem(this.cacheKey);//删除本地的缓存
            connectionobjectsModel.reset();
            entrustaccountsModel.reset();
            menuModel.reset();
            organizationModel.reset();
            userModel.reset();
            versionModel.reset();
        }


    })
    return new Widget();
})
